package aiRpc

import (
	"context"
	"encoding/json"
	"sync"
	"time"

	"google.golang.org/grpc"

	"gitee.com/wulalade/hwpack/lpr/aiApiT"
	pb "gitee.com/wulalade/hwpack/lpr/proto"
)

const (
	// Address 连接地址
	address string = "127.0.0.1:19090"
)

type aiRpcT struct {
	conn       *grpc.ClientConn
	grpcClient pb.GreeterSimpleClient
	totalMutex sync.Mutex
}

var aiRpcH aiRpcT

func init() {
	go scheduled()

}

func task(aiRpc *aiRpcT) {
	if aiRpc.conn == nil {
		ctx1, cel := context.WithTimeout(context.Background(), time.Second*3)
		defer cel()
		conn, err := grpc.DialContext(ctx1, address, grpc.WithBlock(), grpc.WithInsecure())
		if err == nil {
			//赋值
			aiRpcH.conn = conn
			aiRpcH.grpcClient = pb.NewGreeterSimpleClient(conn)
		}
	}
}

//定时任务
func scheduled() {
	for {
		task(&aiRpcH)
		time.Sleep(time.Second * 10)
	}
}

func GetAiServerValue(req *aiApiT.ReqProtocol) (*aiApiT.RspProtocol, int) {
	aiRpcH.totalMutex.Lock()
	defer aiRpcH.totalMutex.Unlock()

	res := aiApiT.RspProtocol{}
	if aiRpcH.conn == nil {
		return &res, 1
	}
	reqByte, err := json.Marshal(req)
	if err != nil {
		return &res, 2
	}
	reqPb := pb.SimpleRequest{
		Data: string(reqByte),
	}
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second*5)
	defer cancel()
	resPb, err := aiRpcH.grpcClient.Route(ctx, &reqPb)
	if err != nil {
		if aiRpcH.conn != nil {
			aiRpcH.conn.Close()
			//发送错误,断开rpc连接
			aiRpcH.conn = nil
		}
		return &res, 3
	}

	ret := json.Unmarshal([]byte(resPb.Value), &res)
	if ret != nil {
		return &res, int(resPb.Code)
	}

	return &res, int(resPb.Code)
}
